import {
  GetPage,
  Save,
  Delete,
  GetNewUserId,
  GetAllOrganization
} from "@/api/admin/teacher";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";

export function useOrganization() {
  const form = reactive({
    OrganizationId: ""
  });

  const updateTeacherDto = reactive({
    UserId: "",
    OrganizationId: "",
    PassWord: "",
    UserName: "",
    Sex: 1,
    TelePhone: "",
    Email: "",
    RoleType: "Tea"
  });

  const sex = ref([
    { id: 1, name: "男" },
    { id: 2, name: "女" }
  ]);
  const organizationList = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const OrganizationInputDisabled = ref(false);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref("修改");

  const checkEmail = (rules, value, cb) => {
    const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    if (value == "") {
      return cb();
    }
    if (regEmail.test(value)) {
      return cb();
    }
    cb(new Error("请输入合法的邮箱"));
  };

  const checkMobile = (rules, value, cb) => {
    const regMobile =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    if (value == "") {
      return cb();
    }

    if (regMobile.test(value)) {
      return cb();
    }
    cb(new Error("请输入合法的手机号"));
  };

  const rules = {
    OrganizationId: [
      {
        required: true,
        message: "请选择机构名称！",
        trigger: ["blur", "change"]
      }
    ],
    UserId: [
      {
        required: true,
        message: "请输入账号！",
        trigger: ["blur", "change"]
      },
      {
        min: 4,
        message: "账号长度不能小于4位数!"
      }
    ],
    PassWord: [
      {
        required: true,
        message: "请输入密码！",
        trigger: ["blur", "change"]
      },
      {
        min: 6,
        message: "密码长度不能小于6位数!"
      }
    ],
    UserName: [
      {
        required: true,
        message: "请输入姓名！",
        trigger: ["blur", "change"]
      }
    ],
    Sex: [
      {
        required: true,
        message: "请选择性别！",
        trigger: ["blur", "change"]
      }
    ],
    TelePhone: [
      {
        required: false,
        message: "请输入手机号码！",
        trigger: ["change"]
      },
      {
        validator: checkMobile,
        trigger: ["change"]
      }
    ],
    Email: [
      {
        required: false,
        message: "请输入邮箱！",
        trigger: ["blur"]
      },
      {
        validator: checkEmail,
        trigger: ["change"]
      }
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "账号",
      prop: "userId",
      minWidth: 100
    },
    {
      label: "密码",
      prop: "passWord",
      minWidth: 100
    },
    {
      label: "姓名",
      prop: "userName",
      minWidth: 100
    },
    {
      label: "性别",
      prop: "sex",
      minWidth: 50,
      cellRenderer: ({ row }) => (
        <el-tag type={row.sex === 2 ? "danger" : ""} effect="plain">
          {row.sex === 1 ? "男" : "女"}
        </el-tag>
      )
    },
    {
      label: "联系电话",
      prop: "telePhone",
      minWidth: 100
    },
    {
      label: "邮箱",
      prop: "email",
      minWidth: 200
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await Delete({ userId: row.userId });
      if (res.success) {
        ElMessage.success(res.msg);
        onSearch();
      } else {
        ElMessage.error(res.msg);
      }
    }).catch(() => { })

    // await Delete({ userId: row.userId });
    // ElMessage({
    //   message: "删除成功",
    //   type: "success"
    // });
    // onSearch(form.OrganizationId);
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const res = await GetPage({
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize,
      organizationId: form.OrganizationId
    });
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount;
      loading.value = false;
    } else {
      ElMessage.error(res.msg)
    }

  }

  const addTeacher = (TeacherToRef: FormInstance | undefined) => {
    (TeacherToRef as any).validate(async valid => {
      if (!valid) return;
      const respone = await Save(updateTeacherDto);
      if (respone.status == 200) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        updatePanelVisible.value = false;
        onSearch();
        ClosePanelVisible(TeacherToRef);
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  };

  // 添加教师or修改教师
  async function updateTeaches(row: any | undefined) {
    updatePanelVisible.value = true;
    if (row) {
      loadingTitle.value = "修改";
      nextTick(() => {
        updateTeacherDto.UserId = row.userId;
        updateTeacherDto.OrganizationId = row.organizationId;
        updateTeacherDto.PassWord = row.passWord;
        updateTeacherDto.UserName = row.userName;
        updateTeacherDto.Sex = row.sex;
        updateTeacherDto.TelePhone = row.telePhone;
        updateTeacherDto.Email = row.email;
      });
    } else {
      const userId = await GetNewUserId({ roleType: "Tea" });
      updateTeacherDto.UserId = userId.data;
      updateTeacherDto.PassWord = "888888";
      updateTeacherDto.OrganizationId = form.OrganizationId;
      OrganizationInputDisabled.value = false;
      if (Number(form.OrganizationId)) {
        OrganizationInputDisabled.value = true;
      }
      loadingTitle.value = "添加";
    }
  }

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    if (!row) return;
    updatePanelVisible.value = false;
    row.resetFields();
  }

  //初始化机构名称下拉框
  async function initOrganizationSelect() {
    const respone = await GetAllOrganization();
    // console.log("respone", respone);
    if (respone.success) {
      organizationList.value = respone.data;
    }
  }

  //机构名称下拉框值改变事件
  // async function organizationSelectChange() {
  //根据所选机构查询教师列表
  // }

  onMounted(() => {
    initOrganizationSelect();
  });

  return {
    form,
    rules,
    loading,
    columns,
    dataList,
    loadingTitle,
    pagination,
    updateTeacherDto,
    updatePanelVisible,
    organizationList,
    OrganizationInputDisabled,
    sex,
    onSearch,
    updateTeaches,
    handleDelete,
    ClosePanelVisible,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    addTeacher

  };
}
